import { useForm } from "antd/es/form/Form";
import { memo, useEffect, useImperativeHandle } from "react";
import { Button, Drawer, DrawerProps, Form, Input, Spin } from "antd";
import { QueryObserverResult, RefetchOptions, RefetchQueryFilters } from "react-query";
import { IFormRef, IPage } from "../../../types";
import { ILawsType, useAddLawsType, useUpdateLawsType } from "../../../service/laws-type-service";


type ILawsTypeFormParams = {
    update?: ILawsType;
    open: boolean;
    onRef: React.MutableRefObject<IFormRef | undefined>;
    openFn: (open: boolean) => void;
    refetch: <TPageData>(options?: (RefetchOptions & RefetchQueryFilters<TPageData>) | undefined) => Promise<QueryObserverResult<IPage<ILawsType>, unknown>>
} & DrawerProps

const LawsTypeForm = ({ update, onRef, ...props }: ILawsTypeFormParams) => {

    const [form] = useForm();
    const { mutateAsync: addMutation, isLoading: addIsLoading } = useAddLawsType();
    const { mutateAsync: updateMutation, isLoading: UIsLoading } = useUpdateLawsType();
    useEffect(() => {
        form.setFieldsValue({
            lawsTypeName: update?.lawsTypeName,
            lawsTypeId: update?.lawsTypeId,
        });
    }, [update]);

    /**
   * 更新方法
   */
    const updateHandler = async () => {
        const values = await form.getFieldsValue();
        await updateMutation({ lawsTypeId: update?.lawsTypeId, ...values });
        props.refetch();
        props.openFn(false);
        form.resetFields();
    }

    /**
     * 保存方法
     */
    const saveHandler = async () => {
        const isPass = await form.validateFields();
        if (!isPass) {
            return
        }
        const values = form.getFieldsValue();
        await addMutation({ ...values });
        props.refetch();
        props.openFn(false);
        form.resetFields();
    }

    /**
     * 向外暴露表单的保存和修改
     */
    useImperativeHandle(onRef, () => ({
        reset: () => {
            form.resetFields();
        },
        save: () => {
            saveHandler();
        },
        update: async () => {
            updateHandler();
        }
    }));

    return (
        <Drawer title={'法律分类'} placement="right" width={'35rem'} closable={true} onClose={() => props.openFn(false)} forceRender={true} open={props.open} footer={
            <>
                {
                    update ? (
                        <Button onClick={() => { updateHandler(); }}>
                            修改
                        </Button>
                    ) : (
                        <Button onClick={() => { saveHandler(); }}>
                            保存
                        </Button>
                    )
                }
            </>
        }>
            <Spin spinning={addIsLoading || UIsLoading}>
                <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
                    <Form.Item label={'类型名称'} name={'lawsTypeName'} rules={[{ required: true, message: '类型名称不能为空' }]}>
                        <Input />
                    </Form.Item>
                </Form>
            </Spin>
        </Drawer>
    );
};


export default memo(LawsTypeForm)